package com.ruoyi.info.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.config.SecurityConfig;
import com.ruoyi.util.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.info.mapper.CmsAppMapper;
import com.ruoyi.info.domain.CmsApp;
import com.ruoyi.info.service.ICmsAppService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.web.multipart.MultipartFile;

/**
 * appService业务层处理
 * 
 * @author xwj
 * @date 2023-08-01
 */
@Service
public class CmsAppServiceImpl implements ICmsAppService 
{
    @Autowired
    private CmsAppMapper cmsAppMapper;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询app
     * 
     * @param id app主键
     * @return app
     */
    @Override
    public CmsApp selectCmsAppById(Long id)
    {
        return cmsAppMapper.selectCmsAppById(id);
    }

    /**
     * 查询app列表
     * 
     * @param cmsApp app
     * @return app
     */
    @Override
    public List<CmsApp> selectCmsAppList(CmsApp cmsApp)
    {
        return cmsAppMapper.selectCmsAppList(cmsApp);
    }

    /**
     * 新增app
     * 
     * @param cmsApp app
     * @return 结果
     */
    @Override
    public int insertCmsApp(CmsApp cmsApp)
    {
        cmsApp.setCreateTime(DateUtils.getNowDate());
        return cmsAppMapper.insertCmsApp(cmsApp);
    }

    /**
     * 修改app
     * 
     * @param cmsApp app
     * @return 结果
     */
    @Override
    public int updateCmsApp(CmsApp cmsApp)
    {
        cmsApp.setUpdateTime(DateUtils.getNowDate());
        return cmsAppMapper.updateCmsApp(cmsApp);
    }

    /**
     * 批量删除app
     * 
     * @param ids 需要删除的app主键
     * @return 结果
     */
    @Override
    public int deleteCmsAppByIds(String ids)
    {
        return cmsAppMapper.deleteCmsAppByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除app信息
     * 
     * @param id app主键
     * @return 结果
     */
    @Override
    public int deleteCmsAppById(Long id)
    {
        return cmsAppMapper.deleteCmsAppById(id);
    }

    @Override
    public Result uploadApp(SysUser currUser, MultipartFile mfile, String lx) throws Exception {
        String filePath = RuoYiConfig.getProfile() + "/app";
        String profile = RuoYiConfig.getProfile();
        // 上传并返回新文件名称
        String[] allowedExtension = {"apk", "ipa"};
        String fileName = FileUploadUtils.upload(filePath, mfile, allowedExtension);


        String fileName2 = fileName.replace(Constants.RESOURCE_PREFIX, "");
        String localPath = profile + fileName2;

        File file = new File(localPath);


        String basePath = serverConfig.getUrl();

        Date now = new Date();
        String timeStr = DateUtil.format(now, "yyyyMMddHHmmssSSS");
        String batchId = "APP_" + timeStr;

//        Result result = new Result();
//        result.setErrno(0);

        Result result = AppScanUtil.uploadApp(basePath, batchId, file, lx);

        if(result.isError()) {
            return result;
        }

        String data = result.getData();
        UploadVo uploadVo = JSON.parseObject(data, UploadVo.class);
        String md5 = "";
        String stauts = "0";
        String relativeId = "";

        if(uploadVo != null) {
            if(uploadVo.getUploads() != null && uploadVo.getUploads().size() > 0) {
                md5 = Convert.toStr(uploadVo.getUploads().get(0).get("file_md5"));
                stauts = Convert.toStr(uploadVo.getUploads().get(0).get("status"));
                relativeId = Convert.toStr(uploadVo.getUploads().get(0).get("id"));
            }
        }

        CmsApp app = new CmsApp();
        app.setUserId(currUser.getUserId());
        app.setName(mfile.getOriginalFilename());
        app.setAttachPath(fileName);
        app.setCreateTime(now);
        app.setBatchId(batchId);
        app.setMd5(md5);
        app.setExt1(lx);
        app.setStatus(stauts);
        app.setRelativeId(relativeId);

        insertCmsApp(app);
        return result;
    }

    @Override
    public CmsApp selectCmsAppByBatchId(String batchId) {
        return cmsAppMapper.selectCmsAppByBatchId(batchId);
    }

    @Override
    public Result refreshRemote(CmsApp app) {
        Result result = AppScanUtil.refreshRemote(app);

        if(result.isError()) {
            return result;
        }
        String data = result.getData();
        List<QueryResultVo> vos =  JSON.parseArray(data, QueryResultVo.class);

        if(vos != null && vos.size() > 0) {
            BasicInfo basicAppInfo = vos.get(0).getReport().getBasicAppInfo();
            String relateId = vos.get(0).getId();
            String status = vos.get(0).getStatus();

            if(basicAppInfo != null) {
                if("apk".equals(app.getExt1())) {
                    app.setPackName(basicAppInfo.getPackageName());
                    app.setAppName(basicAppInfo.getAppName());
                    app.setVersion(basicAppInfo.getVersionName());
                    app.setSize(basicAppInfo.getFileSize());
                } else {
                    app.setPackName(basicAppInfo.getBundle_id());
                    app.setAppName(basicAppInfo.getDisplay_name());
                    app.setVersion(basicAppInfo.getBundle_version());
                    app.setSize(basicAppInfo.getSize());
                }
            }
            app.setExt2(data);
            app.setStatus(status);
            app.setRelativeId(relateId);
            this.updateCmsApp(app);
        }

        return result;
    }

    @Override
    public List<CmsApp> findNotSuccess() {
        return cmsAppMapper.findNotSuccess();
    }

    @Override
    public void getRemoteDetails(CmsApp app) {
        Result result = AppScanUtil.getRemoteDetails(app);
        if(result.isError()) {
            return;
        }
        // 注意这里的data不是数组
        String data = result.getData();
        QueryResultVo vo = JSON.parseObject(data, QueryResultVo.class);

        String relateId = vo.getId();
        String status = vo.getStatus();

        BasicInfo basicAppInfo = vo.getReport().getBasicAppInfo();
        if(basicAppInfo != null) {
            if("apk".equals(app.getExt1())) {
                app.setPackName(basicAppInfo.getPackageName());
                app.setAppName(basicAppInfo.getAppName());
                app.setVersion(basicAppInfo.getVersionName());
                app.setSize(basicAppInfo.getFileSize());
            } else {
                app.setPackName(basicAppInfo.getBundle_id());
                app.setAppName(basicAppInfo.getDisplay_name());
                app.setVersion(basicAppInfo.getBundle_version());
                app.setSize(basicAppInfo.getSize());
            }
        }
        app.setExt2(data);
        app.setStatus(status);
        app.setRelativeId(relateId);
        this.updateCmsApp(app);
    }

}
